/**
 * \license
 * Copyright Lassi Marttala 2013
 * 
 * This file is part of dlt2jpa.
 *
 * dlt2jpa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dlt2jpa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dlt2jpa.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.fizzl.dlt.message.parser;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import net.fizzl.dlt.message.DltStandardHeader;

public class DltStandardHeaderParser {

	public DltStandardHeader fromByteArray(byte[] currentBuffer) {
		DltStandardHeader ret = new DltStandardHeader();
		ByteBuffer buf = ByteBuffer.wrap(currentBuffer);
		
		byte attributes = buf.get();
		ret.setMessageCounter(buf.get());
		ret.setMessageLength(buf.getShort());
		
		if(0 != (attributes & bmExtendedHeader)) ret.setUseExtendedHeader(true);
		if(0 != (attributes & bmBigEndian)) ret.setUseBigEndian(true);
		
		if(0 !=(attributes & bmEcuId)) {
			ret.setUseEcuId(true);
			byte ecuid[] = new byte[5];
			ecuid[0] = buf.get();
			ecuid[1] = buf.get();
			ecuid[2] = buf.get();
			ecuid[3] = buf.get();
			ecuid[4] = 0;
			try {
				ret.setDeviceId(new String(ecuid, "US-ASCII"));
			} catch (UnsupportedEncodingException e) {
			}
		}
		
		if(0 != (attributes & bmSessionId)) {
			ret.setSessionNumber(buf.getInt());
		}
		
		if(0 != (attributes & bmTimestamp)) {
			ret.setTimeStamp(buf.getInt());
		}
		
		ret.setProtocolVersion((attributes & bmProtocolVersion) >> 5);
		if(ret.getProtocolVersion() != 1) {
			// Possible stream corruption
			return null;
		}
		ret.setLength(buf.position());
		return ret;
	}
	
	// Bitmasks for interpreting first header.
	static final int bmExtendedHeader	= 0b00000001; 
	static final int bmBigEndian		= 0b00000010; 
	static final int bmEcuId			= 0b00000100; 
	static final int bmSessionId		= 0b00001000; 
	static final int bmTimestamp		= 0b00010000; 
	static final int bmProtocolVersion	= 0b11100000;
}
